package com.aidex.biz.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;

/**
 * AES加密器
 * <p>
 * 默认128位加密
 *
 * @author fanshiqi
 */
public class RAESUtils {

    public static final String CHAR_ENCODING = "UTF-8";

    public static final String AES_ALGORITHM = "AES";

    public static final String AES_KEY = "123456_qwerty_..";

    public static final Integer SIXTEEN = 16;

    /**
     * 加密
     *
     * @param data 待加密内容
     * @param key  加密秘钥
     * @return 十六进制字符串
     */
    public static String encrypt(String data, String key) {
        if (key.length() < SIXTEEN) {
            throw new RuntimeException("Invalid AES key length (must be 16 bytes)");
        } else if (key.length() > SIXTEEN) {
            key = key.substring(0, 16);
        }
        try {
            // 创建密码器
            Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
            byte[] byteContent = data.getBytes(CHAR_ENCODING);
            // 初始化
            cipher.init(Cipher.ENCRYPT_MODE, genKey(key));
            byte[] result = cipher.doFinal(byteContent);
            // 加密
            return parseByte2HexStr(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 解密
     *
     * @param data 待解密内容(十六进制字符串)
     * @param key  加密秘钥
     * @return
     */
    public static String decrypt(String data, String key) {
        if (key.length() < SIXTEEN) {
            throw new RuntimeException("Invalid AES key length (must be 16 bytes)");
        } else if (key.length() > SIXTEEN) {
            key = key.substring(0, 16);
        }
        try {
            byte[] decryptFrom = parseHexStr2Byte(data);
            // 创建密码器
            Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
            // 初始化
            cipher.init(Cipher.DECRYPT_MODE, genKey(key));
            byte[] result = cipher.doFinal(decryptFrom);
            // 加密
            return new String(result, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建加密解密密钥
     *
     * @param key 加密解密密钥
     * @return
     */
    private static SecretKeySpec genKey(String key) {
        SecretKeySpec secretKey;
        try {
            secretKey = new SecretKeySpec(key.getBytes(CHAR_ENCODING), AES_ALGORITHM);
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec seckey = new SecretKeySpec(enCodeFormat, AES_ALGORITHM);
            return seckey;
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("genKey fail!", e);
        }
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    private static String parseByte2HexStr(byte[] buf) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        String data="Un146rxYhlBZ7osrH76vI0xL2txUTo9n\\/DODTPhRAdcYSLwMm5V\\/h1rHrPmNaXQP7Y5pPZgvlEW6KUP7DrQ8k+WId0+A+bZWkPe2OHMXxVOyWiiQguvYVfMY1t+\\/2cvrnJpCls+1pjo333X+ufKCZQkgMVL48SbmMmezEHKDOSPScIvXjShDT5IIfEA71jdFbL5N8LmJ5Bjj1Sfg7sk\\/zbz\\/Z78RbPUvDn0p\\/EYI74OafthDYQs5pbiXgtxl50dhoyY+sfOHKTDiRBXkCK7q4O+\\/QZVivoHHsDaLnHit0CkdiaYRPgZPH4rQ4sEc9tbqZacCeU2j4b8hYfbkVeYdm7ctrXB539\\/FqIKfKqWng4gOCc\\/ISCmCS6kI4Q465v9CrMQ9\\/zbiSK2zHHM+b2tQqFQjrhvN0dPHoC5XnJws7zhJGgINvmyOSiZeZJZX00KxUIJ2wlTh567lL3DzWhS0cBt\\/ickStv9qYkV6YTsxP3jT45olCiVmdfEaahzcm02c\\/nPEknBuSnBT7xWB\\/Lb1mAfHahgLxX5i9+F0KuGLLYejdqpWnNNODs6MD8dKTfuvY0pjwV1iKaeutByiPtQDjWToDJwpUwBet2zJ0XYibn5QhJRW6rKwew6m398kpsIlBeiSNw+vBzhd3pK\\/Ulap+QK\\/dLVj8On2a6xbId\\/Gj0M=";
       // System.out.println(AESUtils.Decrypt(data, "Mi0FDuAaVtuRQFEA"));

    }

}
